<template><!--团队排行-->
    <div id="test">
        <table-body :options="initObj" ref="table"></table-body>
    </div>
</template>
<script>
    import {getSuperTeamRank,downloadSceneAllReport,downloadFile,submitRecord} from '@/api/compitionStatic'
    import {ctfReport} from '@/api/drill_compete'
    import {getaccessgroupmember} from '@/api/access_new'
    import tableBody from './tableListComponent'
    import groupMixin from "@/mixin/groupMixin";
    export default {
        name: 'scenes',
        props:['sceneId','poll'],
        mixins: [groupMixin],
        data(){
            const d = function(val){
                this.getRankingStatic(null,null,val)
            }.bind(this);
            const exportFile = function(val){
                this.exportFile();
            }.bind(this);
            const exportScoreRecord = function(val){
                this.exportScoreRecord();
            }.bind(this);
            const downloadAllReport = function(val){
                this.downloadAllReport();
            }.bind(this);
            return {
                selFiles:[],
                initObj:{
                    Button:[
                    ],
                    Input:[
                    ],
                    Select:[
                        {
                            optionsValue: [],
                            placeholder: `请选择大组`,
                            fnName: this.getRankingStaticById
                        }
                    ],
                    DatePicker:{
                        isShow:false,
                        fnName:d,
                    },
                    Page:{
                        total:0,
                        currentPage:1,
                        pageSize:10
                    },
                    Table:{
                        listCol:[
                            {
                                align: 'center',
                                key:'rank',
                                placement:'top-right',
                                order:1,
                                render:(h,params) => {
                                    let ele;
                                    if(params.row._index < 3 && this.curPage == 1){
                                        ele = h('img',{
                                            attrs:{
                                                src:require(`../../../../assets/scene/top${params.row._index+1}.png`)
                                            },
                                            style:{
                                                display:'inline-block',
                                                verticalAlign: 'text-bottom',
                                                marginLeft: '20px'
                                            }
                                        })
                                    }else{
                                        ele = h('span',params.row._index+1 + (this.curPage-1)*10)
                                    }
                                    let index = params.row._index+1;
                                    let color = '#000';
                                    if(this.curPage == 1){
                                        if(index == 1){
                                            color = '#f34938';
                                        }else if(index == 2){
                                            color = '#eb8205';
                                        }else if(index == 3){
                                            color = '#27b666';
                                        }else{
                                            color = '#000'
                                        }
                                    }
                                    return h('span',[
                                        h('span',{
                                            style:{
                                                color:color
                                            }
                                        },'排行'),
                                        ele
                                    ]);
                                }
                            },
                            {
                                title:'大组名称',
                                key:'teamName',
                                align:'center',
                                ellipsis:true,
                                tooltip:true,
                                placement:'top-left',
                                order:1,
                                width: 240
                            },
                            {
                                title:'得分',
                                key:'totalScore',
                                align:'center',
                                ellipsis:true,
                                tooltip:true,
                                width:60,
                            },
                            {
                                title:'解决题目数',
                                key:'finishTotal',
                                align:'center',
                                width:60
                            },
                            {
                                title:'未解决题目数',
                                key:'notFinishTotal',
                                align:'center',
                                width:60,
                            },
                            {
                                title:'撤销数',
                                key:'cheatTotal',
                                align:'center',
                                width:60,
                            },
                            {
                                title:'团队成员',
                                key:"groupUsrs",
                                render:(h,params) => {
                                    let tagArr = [];
                                    tagArr = params.row.groupUsers && params.row.userList.map(user => {
                                        return h('Tag',{
                                            props:{
                                                color:'purple'
                                            }
                                        },user.userName);
                                    })
                                    return h('span',tagArr.length > 0 ? tagArr : '无')
                                }
                            }
                        ],
                        listData:[]
                    },
                    Fnlist:'getRankingStatic',
                },
                selName:'',
                timeout:{},
                curPage:1,
                pdfUrl:'',
                pdfModal:false,
                submitRecordModal:false,
                listCol:[
                    {
                        type: 'index',
                        align: 'center',
                        ellipsis:true,
                        width:60
                    },
                    {
                        title:'题目名称',
                        key:'targetName',
                        align:'center',
                        ellipsis:true,
                        tooltip:true,
                    },
                    {
                        title:'提交者',
                        key:'userName',
                        align:'center',
                        ellipsis:true,
                        tooltip:true,
                    },
                    {
                        title:'提交内容',
                        key:'content',
                        align:'center',
                        ellipsis:true,
                        tooltip:true,
                    },
                    {
                        title:'提交时间',
                        key:'createTime',
                        align:'center',
                        ellipsis:true,
                        tooltip:true
                    },
                    {
                        title:'得分',
                        key:'score',
                        align:'center',
                        ellipsis:true,
                        placement:'top-right',
                        render:(h,params) => {
                            return h('Tag',{
                                props:{
                                    color:params.row.score > 0 ? 'success' :'default',
                                    type:"border"
                                },
                                on:{
                                    click:()=>{
                                    }
                                }
                            }, params.row.isRight == 1 ? params.row.score : 0 )
                        }
                    }
                ],
                rightSubmitList:[],
                rightSubmitTotal:0,
                supergroupList: []
            }
        },
        components:{
            'table-body':tableBody,
        },
        watch:{
            teamList(newValue) {
                let supergroupList = []
                let idList = []
                if (newValue) {
                    newValue.forEach(item => {
                        let description = item.description
                        if (description && !idList.includes(description)) {
                            supergroupList.push({
                                id: description,
                                name: description
                            })
                            idList.push(description)
                        }
                    })
                }
                this.supergroupList = supergroupList
                this.initObj.Select[0].optionsValue = supergroupList
            }
        },
        created(){
        },
        beforeDestroy(){
            clearTimeout(this.timeout)
        },
        mounted(){
            this.getRankingStatic();
        },
        methods:{
            getTeamNameById(id) {
                let team = this.supergroupList.find(item => {
                    return item.id === id
                })
                return team ? team.name : ''
            },
            getRankingStaticById(id) {
                this.selName = this.getTeamNameById(id);
                this.initObj.Page.currentPage = 1
                this.initObj.Page.pageSize = 10
                this.$refs.table.resetPage()
                this.getRankingStatic();
            },
            async getRankingStatic(page,pageSize,querytime){
                let _this = this;
                let pages = page || 1;
                this.$set(this.initObj.Page, 'currentPage', pages)
                let rows = pageSize||_this.initObj.Page.pageSize|| 10;
                let params={
                    pageIndex : pages,
                    pageSize : rows
                };
                this.curPage = pages;
                if(this.selName){
                    params.teamName =  this.selName;
                }
                if(_this.$route.query.id){
                    params.sceneId = _this.$route.query.id
                    getSuperTeamRank(params).then(data=>{
                        if(data.code==1){
                            let listData = data.data.items;
                            let proArr = listData.map(async item => {
                                this.$set(item,'fileId','');
                                this.$set(item,'fileName','');
                                this.$set(item,'groupUsers',[]);
                                if(item.report == 1){
                                    await this.ctfReport(item);
                                }
                                await this.getaccessgroupmember(item);
                            })
                            Promise.all(proArr).then(data => {
                                _this.initObj.Table.listData = listData;
                            })
                            _this.initObj.Page.total = data.data.total;
                            clearTimeout(this.timeout)
                            if(this.poll){ //如果需要轮询
                                this.timeout = setTimeout(() => {
                                    this.getRankingStatic(page,pageSize);
                                },3000)
                            }
                        }
                    })
                }
            },
            saveInfo(val){
            },
            exportFile(){
                let sceneId = this.$route.query.id;
                let sceneName = this.$route.query.name;
                let a = document.createElement("a");
                document.body.appendChild(a);
                a.href = `/api/compete/ctfGameBox/export/${sceneId}/${sceneName}`;
                a.download = ''; //命名下载名称
                a.click(); //点击触发下载
                a.remove();
            },
            exportScoreRecord(){
                let sceneId = this.$route.query.id;
                let sceneName = this.$route.query.name;
                let a = document.createElement("a");
                document.body.appendChild(a);
                a.href = `/api/compete/ctfGameBox/exportSubmit/${sceneId}/${sceneName}`;
                a.download = ''; //命名下载名称
                a.click(); //点击触发下载
                a.remove();
            },
            ctfReport(item){
                return new Promise(resolve => {
                    let sceneId = this.$route.query.id;
                    let teamId = item.teamId;
                    ctfReport(sceneId,teamId).then(data => {
                        if(data.code == 1 && data.data && data.data.length){
                            this.$set(item,'fileId',data.data[0].fileId);
                            this.$set(item,'fileName',data.data[0].fileName);
                            resolve(true);
                        }else{
                            resolve(false);
                        }
                    }).catch(error => {
                        resolve(false);
                    })
                })
            },
            //获取团队成员
            getaccessgroupmember(group){
                return new Promise(resolve => {
                    getaccessgroupmember(group.teamId).then(data => {
                        if(data.code == 1){
                            group.groupUsers = data.data;
                            resolve(true);
                        }else{
                            this.$Message.error('获取团队成员失败！');
                            resolve(false);
                        }
                    }).catch(error => {
                        this.$Message.error('获取团队成员失败！');
                        resolve(false);
                    })
                })
            },
            downloadAllReport(){
                let sceneId = this.$route.query.id;
                downloadSceneAllReport(sceneId,[]).then(data => {
                    if(data.type == 'application/octet-stream'){
                        const downloadElement = document.createElement("a");
                        const href = window.URL.createObjectURL(data);
                        downloadElement.href = href;
                        downloadElement.download = '解题报告.zip';
                        document.body.appendChild(downloadElement);
                        downloadElement.click();
                        document.body.removeChild(downloadElement); // 下载完成移除元素
                        window.URL.revokeObjectURL(href); // 释放掉blob对象
                    }else{
                        this.$Message.error('下载报告失败!不存在文件数据！');
                    }
                }).catch(error => {
                    this.$Message.error('下载报告失败!');
                })
            },
            downloadFile(team){
                downloadFile(team.fileId).then(data => {
                    if(!data.code){
                        const downloadElement = document.createElement("a");
                        const href = window.URL.createObjectURL(data);
                        downloadElement.href = href;
                        downloadElement.download = team.teamName + '.' +team.fileName.split('.').pop();
                        document.body.appendChild(downloadElement);
                        downloadElement.click();
                        document.body.removeChild(downloadElement); // 下载完成移除元素
                        window.URL.revokeObjectURL(href); // 释放掉blob对象
                    }else{
                        this.$Message.error(data.message);
                    }
                }).catch(error => {
                    this.$Message.error('下载报告失败!');
                })
            },
            getAttackSuccess(team){
                let params={
                    pageIndex : 1,
                    pageSize : 2147483647,
                    sceneId:this.$route.query.id,
                    isRight:1,
                    teamId:team.teamId
                };
                submitRecord(params).then(data=>{
                    if(data.code==1){
                        this.rightSubmitList = data.data.items;
                        this.rightSubmitTotal = data.data.total;
                    }else{
                        this.$Message.error(data.message);
                    }
                }).catch(error => {
                    this.$Message.error(data.message);
                })
            },
        },
    }
</script>

<style>
    .drillsTable .ivu-poptip-body {
        text-align: left!important;
    }
    .scenesHeader{
        margin-bottom: 16px;
    }
    .drillTables{
        min-height: 300px;
    }
    .drillsTable.ivu-table-wrapper{
        overflow: inherit;
    }
</style>
<style scoped>
    .Titles{
        background: #eeeeee;
        margin: 16px auto;
        padding: 10px 0;
    }
    .targetHeader{
        padding: 10px;
        margin-bottom: 10px;
    }
</style>
